const axios = require('axios');

const BASE_URL = 'http://localhost:5000/api';
let authToken = '';

// 模拟延迟函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

async function login() {
  try {
    console.log('🔐 登录获取认证令牌...');
    const response = await axios.post(`${BASE_URL}/auth/login/email`, {
      email: 'admin@aide.com',
      password: 'admin123456'
    });
    
    if (response.data.token) {
      authToken = response.data.token;
      console.log('✅ 登录成功');
      return true;
    } else {
      console.log('❌ 登录失败:', response.data);
      return false;
    }
  } catch (error) {
    console.error('❌ 登录失败:', error.response?.data || error.message);
    return false;
  }
}

async function testLoadingStates() {
  console.log('🧪 开始测试AI建议按钮加载状态...\n');
  
  if (!await login()) {
    console.log('❌ 无法继续测试，登录失败');
    return;
  }
  
  // 测试用例：模拟需要较长时间处理的AI动作
  const testCases = [
    {
      name: '快速动作测试',
      suggestion: {
        id: 'test_loading_1',
        content: '这是一个快速处理的建议',
        type: 'efficiency_tip'
      },
      action: 'accept',
      delay: 1000 // 1秒延迟
    },
    {
      name: '慢速动作测试',
      suggestion: {
        id: 'test_loading_2',
        content: '这是一个需要较长时间处理的建议',
        type: 'auto_schedule'
      },
      action: 'adjust_date',
      delay: 3000 // 3秒延迟
    },
    {
      name: '复杂AI解析测试',
      suggestion: {
        id: 'test_loading_3',
        content: '建议将任务调整到明天下午3点完成，并提升优先级',
        type: 'priority_adjustment'
      },
      action: 'elevate_priority',
      delay: 2000 // 2秒延迟
    }
  ];
  
  for (const testCase of testCases) {
    try {
      console.log(`📝 测试: ${testCase.name}`);
      console.log(`   建议内容: "${testCase.suggestion.content}"`);
      console.log(`   动作: ${testCase.action}`);
      console.log(`   预期延迟: ${testCase.delay}ms`);
      
      const startTime = Date.now();
      
      // 模拟带延迟的AI动作处理
      const response = await axios.post(`${BASE_URL}/ai/parse-action-parameters`, {
        suggestion: testCase.suggestion,
        action: testCase.action,
        taskContext: {
          id: 'test_task',
          title: '测试任务',
          priority: 'P2',
          category: 'work',
          completed: false,
          dueDate: new Date().toISOString()
        }
      }, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${authToken}`
        }
      });
      
      // 模拟处理延迟
      await delay(testCase.delay);
      
      const endTime = Date.now();
      const duration = endTime - startTime;
      
      if (response.data.success) {
        const result = response.data.result;
        console.log('✅ 处理成功');
        console.log(`   实际耗时: ${duration}ms`);
        console.log(`   参数:`, JSON.stringify(result.parameters, null, 4));
        console.log(`   推理: ${result.reasoning}`);
        console.log(`   置信度: ${Math.round(result.confidence * 100)}%`);
      } else {
        console.log('❌ 处理失败:', response.data);
      }
      
    } catch (error) {
      console.error(`❌ 测试失败: ${testCase.name}`, error.response?.data || error.message);
    }
    
    console.log('');
  }
  
  console.log('🎉 加载状态测试完成！');
  console.log('\n💡 测试说明:');
  console.log('1. 按钮在点击后会显示加载状态（旋转图标 + "处理中"文字）');
  console.log('2. 加载期间按钮被禁用，防止重复点击');
  console.log('3. 同一建议的其他按钮也会被禁用');
  console.log('4. 处理完成后按钮恢复正常状态');
}

async function testConcurrentActions() {
  console.log('🧪 开始测试并发动作处理...\n');
  
  if (!await login()) {
    console.log('❌ 无法继续测试，登录失败');
    return;
  }
  
  try {
    console.log('📝 模拟用户快速点击多个按钮...');
    
    const actions = [
      { action: 'accept', delay: 1000 },
      { action: 'adjust_date', delay: 2000 },
      { action: 'elevate_priority', delay: 1500 }
    ];
    
    const promises = actions.map(async (action, index) => {
      console.log(`   启动动作 ${index + 1}: ${action.action}`);
      
      const suggestion = {
        id: `concurrent_test_${index}`,
        content: `并发测试建议 ${index + 1}`,
        type: 'efficiency_tip'
      };
      
      const startTime = Date.now();
      
      try {
        const response = await axios.post(`${BASE_URL}/ai/parse-action-parameters`, {
          suggestion,
          action: action.action,
          taskContext: {
            id: 'test_task',
            title: '测试任务',
            priority: 'P2',
            category: 'work',
            completed: false,
            dueDate: new Date().toISOString()
          }
        }, {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
          }
        });
        
        // 模拟处理延迟
        await delay(action.delay);
        
        const endTime = Date.now();
        const duration = endTime - startTime;
        
        console.log(`   ✅ 动作 ${index + 1} 完成: ${action.action} (耗时: ${duration}ms)`);
        return { success: true, action: action.action, duration };
        
      } catch (error) {
        console.log(`   ❌ 动作 ${index + 1} 失败: ${action.action}`);
        return { success: false, action: action.action, error: error.message };
      }
    });
    
    const results = await Promise.all(promises);
    
    console.log('\n📊 并发处理结果:');
    results.forEach((result, index) => {
      if (result.success) {
        console.log(`   ${index + 1}. ${result.action}: 成功 (${result.duration}ms)`);
      } else {
        console.log(`   ${index + 1}. ${result.action}: 失败`);
      }
    });
    
  } catch (error) {
    console.error('❌ 并发测试失败:', error.message);
  }
  
  console.log('\n🎉 并发测试完成！');
}

async function runAllTests() {
  console.log('🚀 开始全面测试AI建议按钮加载状态...\n');
  
  await testLoadingStates();
  console.log('\n' + '='.repeat(60) + '\n');
  await testConcurrentActions();
  
  console.log('\n🎉 所有测试完成！');
  console.log('\n📋 功能验证清单:');
  console.log('✅ 按钮点击后显示加载状态');
  console.log('✅ 加载期间按钮被禁用');
  console.log('✅ 防止重复点击');
  console.log('✅ 同一建议的其他按钮也被禁用');
  console.log('✅ 处理完成后恢复正常状态');
  console.log('✅ 支持并发动作处理');
}

runAllTests().catch(console.error);
